import warnings
warnings.filterwarnings('ignore')
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(40)

from tensorflow.keras.models import Sequential
from tensorflow.keras import utils, optimizers, losses, metrics
from tensorflow.keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten

batch_size = 128
nb_output = 10
epochs = 3

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255

y_train = utils.to_categorical(y_train, nb_output)
y_test = utils.to_categorical(y_test, nb_output)


model = Sequential([
    Conv2D(6, (5, 5), activation='relu', input_shape=[28, 28, 1]),
    MaxPooling2D((2, 2)),
    Conv2D(16, (3, 3), activation='relu'),
    MaxPooling2D((2, 2)),

    Flatten(),

    Dense(120, activation='relu'),
    Dense(84, activation='relu'),
    Dense(nb_output, activation='softmax')
])

model.summary()  # ValueError: This model has not yet been built. Build the model first by calling `build()` or calling `fit()` with some data, or specify an `input_shape` argument in the first layer(s) for automatic build.

model.compile(loss=losses.CategoricalCrossentropy(),
              optimizer=optimizers.Adam(0.001),
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)

score = model.evaluate(x_test, y_test)
print('loss:', score[0])
print('acc:', score[1])
